﻿#include"stdafx.h"
#ifdef LK_REFLECTION_
namespace LK
{
	namespace Reflection
	{
		PNamespaceNode::PNamespaceNode(PString const& name, WeakPtr<PTypeLibrary> const& library, PNamespaceNode const&baseNode) :PDomainNode(library, baseNode, name){}
		PNamespaceNode PNamespaceNode::FindOrAddNamespace(PString const&name)const{ return Ptr()->FindOrAddNamespace(name); }
		PTypeNode PNamespaceNode::FindOrAddTypeNode(PString const&str,PType const&t)const{ return Ptr()->FindOrAddTypeNode(str,t); }
		/**
		@brief 获取类型节点数组*/
		Collection::PArray<PTypeNode> PNamespaceNode::GetTypeNodeArray()const { return Ptr()->GetTypeNodeArray(); }
		NamespaceNode::NamespaceNode(PString const& name, WeakPtr<PTypeLibrary> const& library, PNamespaceNode const&baseNode)
			: DomainNode(library, baseNode, name){}
		/**
		@brief 获取类型节点数组*/
		Collection::PArray<PTypeNode> NamespaceNode::GetTypeNodeArray()const
		{
			Collection::PArray<PTypeNode>arr((index_t)0);
			PType t = PType::Make<PTypeNode>();
			for (index_t i = 0; i < InnerNodes.GetLength(); ++i)
			if (InnerNodes[i].GetType() == t)arr.Append((PTypeNode&)(InnerNodes[i]));
			return arr;
		}
		PNamespaceNode NamespaceNode::FindOrAddNamespace(PString const&name)
		{
			if (name.IsNullOrEmpty())throw PInvalidArgumentException(L"命名空间的名称不能为空");
			if (name.StartsWith(GetLibrary().GetSeparatorRef()))return GetLibrary().GetGlobleNamespaceRef().FindOrAddNamespace(name.Substring(GetLibrary().GetSeparatorRef().size()));
			Collection::PArray<PString >arr = name.Split(GetLibrary().GetSeparatorRef());//获取命名空间分隔
			PNamespaceNode p=this;
			for (index_t i = 0; i < arr.GetLength(); ++i)
			{
				PLibraryNode x = p.GetInnerNodeByName(arr[i]);
				if (x.IsNull())
					p = Convert<PNamespaceNode,PLibraryNode>::RefFrom(p.AddInnerNode(new NamespaceNode(arr[i])));
				else if (x.CastTo<PNamespaceNode>().IsNull())throw PReflectionException(L"指定的命名空间路径跟现有其它类型子节点同名");
				else p = (PNamespaceNode&)x;
			}
			return p;
		}
		PTypeNode NamespaceNode::FindOrAddTypeNode(PString const& name,PType const&t)
		{
			index_t i = name.LastIndexOf(GetLibrary().GetSeparatorRef());
			if (i>=0)
			{
				PString str = name.Substring(i+1);
				if (i == 0)return GetLibrary().GetGlobleNamespaceRef().FindOrAddTypeNode(str,t);
				return FindOrAddNamespace(name.Substring(0, i)).FindOrAddTypeNode(str,t);
			}
			PTypeNode node = GetInnerNodeByName(name).CastTo<PTypeNode>();
			if (node.IsNull() && !t.IsNull())
			{
				node = new TypeNode(t, name);
				AddInnerNode(node);
			}
			return node;
		}
	}
}
#endif
